<?php

namespace app\modules\admin\services;

use app\common\services\BaseService;
use app\common\services\UploadService;
use app\components\pagination\Pagination;
use app\config\Constants;
use app\models\Merchant;
use app\models\MerchantCategoryRelation;
use app\models\MerchantCredential;
use app\models\MerchantInfo;
use app\modules\admin\forms\merchant\MerchantCredentialForm;
use app\modules\admin\forms\merchant\MerchantForm;
use app\modules\admin\forms\merchant\MerchantInfoForm;
use EasyWeChat\Kernel\Http\StreamResponse;
use yii\helpers\ArrayHelper;

class MerchantService extends BaseService{

    /**
     * 搜索
     * @param $merchant_name
     * @param $cat_id
     * @param $status
     * @param $page
     * @param $pagesize
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($merchant_name, $cat_id, $status, &$page, $pagesize)
    {
        $query = Merchant::find()
            ->asArray(true)
            ->orderBy(['merchant_id'=>SORT_DESC]);

        if(!empty($merchant_name)){
            $query->andWhere(['like','merchant_name',$merchant_name]);
        }
        if(!empty($cat_id)){
            $query->andWhere(['in','merchant_id',MerchantCategoryRelation::find()->select(['merchant_id'])->where(['cat_id'=>$cat_id])->column()]);
        }
        if(!empty($status)){
            $query->andWhere(['status'=>$status]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());

        $data = $query->all();

        $accounts = MerchantCredential::find()
            ->asArray(true)
            ->select(['merchant_id','username'])
            ->andWhere(['type'=>Constants::USERNAME])
            ->andWhere(['in','merchant_id',ArrayHelper::getColumn($data,"merchant_id")])
            ->all();
        $accounts = ArrayHelper::index($accounts,"merchant_id");

        foreach($data as $k=>$v){
            $data[$k]['username'] = isset($accounts[$v['merchant_id']]) ? $accounts[$v['merchant_id']]['username'] : "";
        }

        return $data;
    }

    /**
     * 添加
     * @param MerchantForm $base_form
     * @param MerchantInfoForm $info_form
     * @param MerchantCredentialForm $account_form
     * @return bool
     * @throws \Throwable
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     */
    public static function create(MerchantForm $base_form,MerchantInfoForm $info_form,MerchantCredentialForm $account_form){
        if(!$base_form->validate()){
            self::setError($base_form->getFirstFieldError());
            return false;
        }
        if(!$info_form->validate()){
            self::setError($info_form->getFirstFieldError());
            return false;
        }
        if(!$account_form->validate()){
            self::setError($account_form->getFirstFieldError());
            return false;
        }

        $transaction = \Yii::$app->getDb()->beginTransaction();

        $base = new Merchant();
        $base->setAttributes($base_form->getAttributes(),false);
        $base->setAttribute("cat_name",implode(',',ArrayHelper::getColumn(MerchantCategoryService::getInfoByIds($base_form->cat_id),"cat_name")));
        $base->setAttribute("add_time",date("Y-m-d H:i:s"));
        if($base->insert() === false){
            $transaction->rollBack();
            return false;
        }

        foreach($base_form->cat_id as $v){
            $model = new MerchantCategoryRelation();
            $model->setAttribute("merchant_id",$base->merchant_id);
            $model->setAttribute("cat_id",$v);
            if($model->insert() === false){
                $transaction->rollBack();
                return false;
            }
        }

        $info = new MerchantInfo();
        $info->setAttributes($info_form->getAttributes(),false);
        $info->setAttribute("merchant_id",$base->merchant_id);
        if($info->insert() === false){
            $transaction->rollBack();
            return false;
        }

        $account = new MerchantCredential();
        $account->setAttributes($account_form->getAttributes(),false);
        $account->setAttribute("merchant_id",$base->merchant_id);
        $account->setAttribute("type",Constants::USERNAME);
        $password = \Yii::$app->params['default_password'];
        $account->setAttribute("content",\Yii::$app->getSecurity()->generatePasswordHash($password));
        if($account->insert() === false){
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();

        //创建小程序二维码到七牛
        $wechat = \Yii::$app->wechat->getMiniProgram();
        $path = \Yii::getAlias("@runtime");
        $file = "temp.jpg";
        /**
         * @var StreamResponse $result
         */
        $result = $wechat->app_code->getUnlimit($base->merchant_id,['page'=>'pages/shopping/index']);
        $result->saveAs($path,$file,false);
        $oss_path = UploadService::uploadFileByPath($path.'/'.$file);
        $base->setAttribute("mini_store_img",$oss_path);
        $base->update();

        return true;
    }

    /**
     * 更新
     * @param MerchantForm $base_form
     * @param MerchantInfoForm $info_form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\Exception
     * @throws \yii\db\StaleObjectException
     */
    public static function update(MerchantForm $base_form,MerchantInfoForm $info_form){
        if(!$base_form->validate()){
            self::setError($base_form->getFirstFieldError());
            return false;
        }
        if(!$info_form->validate()){
            self::setError($info_form->getFirstFieldError());
            return false;
        }

        //开启事务
        $transaction = \Yii::$app->getDb()->beginTransaction();

        $base = Merchant::findOne($base_form->merchant_id);
        if(!$base){
            self::setError(\Yii::t("app","商户不存在"));
            return false;
        }
        $base->setAttribute("cat_name",implode(',',ArrayHelper::getColumn(MerchantCategoryService::getInfoByIds($base_form->cat_id),"cat_name")));
        $base->setAttributes($base_form->getAttributes(),false);
        if($base->update() === false){
            $transaction->rollBack();
            return false;
        }

        MerchantCategoryRelation::deleteAll(['merchant_id'=>$base->merchant_id]);
        foreach($base_form->cat_id as $v){
            $model = new MerchantCategoryRelation();
            $model->setAttribute("merchant_id",$base->merchant_id);
            $model->setAttribute("cat_id",$v);
            if($model->insert() === false){
                $transaction->rollBack();
                return false;
            }
        }

        $info = MerchantInfo::findOne($base_form->merchant_id);
        $info->setAttributes($info_form->getAttributes(),false);
        if($info->update() === false){
            $transaction->rollBack();
            return false;
        }
        $transaction->commit();
        return true;
    }

    /**
     * 获取信息
     * @param $id
     * @return array
     */
    public static function getInfoById($id){
        $data = [];
        $merchant = Merchant::findOne($id);
        if(!$merchant){
            return [];
        }
        $data['base'] = $merchant->toArray();
        $data['base']['cat_id'] = MerchantCategoryRelation::find()->select("cat_id")->where(['merchant_id'=>$id])->column();
        $data['info'] = $merchant->merchantInfo;
        return $data;
    }

    /**
     * 更新状态
     * @param $id
     * @param $status
     * @return bool|void
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function updateStatusById($id, $status)
    {
        $merchant = Merchant::findOne($id);
        if(!$merchant){
            return;
        }
        $merchant->setAttribute("status",$status);
        return $merchant->update() !== false;
    }

    /**
     * 重置密码
     * @param $id
     * @param $password
     * @return bool
     * @throws \Throwable
     * @throws \yii\base\Exception
     * @throws \yii\db\StaleObjectException
     */
    public static function password($id,$password){
        if(empty($password)){
            self::setError(\Yii::t("app","密码不能为空"));
            return false;
        }
        if(strlen($password) < 6){
            self::setError(\Yii::t("app","密码不能少于6位"));
            return false;
        }
        $model = MerchantCredential::findOne(['merchant_id'=>$id,'type'=>'1']);
        if(!$model){
            self::setError(\Yii::t("app","商户不存在"));
            return false;
        }
        $model->setAttribute("content",\Yii::$app->getSecurity()->generatePasswordHash($password));
        return $model->update() !== false;
    }
}